package com.hooper.login.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.interfaces.*;
import com.hooper.login.entity.Result;
import com.hooper.login.entity.UserDto;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class JWTUtil {

    private static final String SECRET = "!Q@W#E$R^Y&U";
    //token签发者
    private static final String ISSUER = "timhooper";
    //token过期时间 30分
    public static final Long EXPIRE_DATE = 1000 * 60 * 30L;

    /**
     * 生成token
     *
     * @param userDto
     * @return
     */
    public static String getToken(UserDto userDto) {
        //当前时间
        Date now = new Date();
        //1. header
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_DATE))
                .withClaim("name", userDto.getName())
                .withClaim("id", userDto.getId())
                .withClaim("role", userDto.getRole())
                .sign(algorithm);
        return token;
    }

    /**
     * 生成token
     *
     * @param map
     * @return
     */
    public static String createToken(Map<String, String> map) {
        //创建过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);  //7天过期

        //创建builder对象
        JWTCreator.Builder builder = JWT.create();
        //遍历map
        map.forEach(builder::withClaim);
        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证token
     * 验证过程中如果有异常，则抛出；
     * 如果没有,则返回 DecodedJWT 对象来获取用户信息;
     *
     * @param token
     */
    public static Result verifyToken(String token, String username) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        try {
            JWTVerifier jwtVerifier = JWT.require(algorithm).withClaim("username", username).build();
            jwtVerifier.verify(token);
            return Result.ok();
        } catch (SignatureVerificationException e) {
            //验证的签名不一致
            throw new SignatureVerificationException(algorithm);
        } catch (TokenExpiredException e) {
            throw new TokenExpiredException("token is alreadey expired");
        } catch (AlgorithmMismatchException e) {
            throw new AlgorithmMismatchException("签名算法不匹配");
        } catch (InvalidClaimException e) {
            throw new InvalidClaimException("校验的claims内容不匹配");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("用户和jwt-token校验失败");
    }

    /**
     * 验证token
     * 验证过程中如果有异常，则抛出；
     * 如果没有,则返回 DecodedJWT 对象来获取用户信息;
     *
     * @param token
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 验证token
     * 验证过程中如果有异常，则抛出；
     * 如果没有,则返回 DecodedJWT 对象来获取用户信息;
     *
     * @param token
     */
    public static UserDto getUserVo(String token) {
        DecodedJWT verify = verify(token);
        String name = verify.getClaim("name").asString();
        Long id = verify.getClaim("id").asLong();
        UserDto userDto = new UserDto();
        userDto.setId(id);
        userDto.setName(name);
        userDto.setRole(verify.getClaim("role").asString());
        return userDto;
    }
}

